package com.ruoyi.system.delay;

import com.ruoyi.system.service.IHospitalSubscribeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.DelayQueue;

@Component
public class DelayQueueManager {

    private static final DelayQueue<DelayOrderTask> queue = new DelayQueue<>();

    @Autowired
    private IHospitalSubscribeOrderService hospitalSubscribeOrderService;


    @PostConstruct
    public void init(){
        new Thread(()->{
            while (true){
                try {
                    DelayOrderTask take = queue.take();
                    closeOrder(take.getOrderNo());
                } catch (InterruptedException e) {
                  Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

    /**
     * 添加订单
     * @param orderNo
     * @param delayMinutes
     */
    public void addOrder(String orderNo, Long delayMinutes) {
        queue.put(new DelayOrderTask(orderNo, delayMinutes));
    }

    /**
     * 关闭订单
     * @param orderNo
     */
    private void closeOrder(String orderNo) {
        hospitalSubscribeOrderService.closeOrderByOrderNo(orderNo);
    }

}
